import java.io.BufferedInputStream;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStream;
import java.rmi.*;
import java.rmi.server.*;
import java.security.Key;
import java.security.MessageDigest;
import java.util.Random;

import javax.crypto.Cipher;
import javax.crypto.spec.SecretKeySpec;

import sun.misc.BASE64Decoder;
import sun.misc.BASE64Encoder;

public class TGService extends UnicastRemoteObject implements TGServiceInterface {

	private static final String ALGORITHM = "AES";
	
	//First col will be service ID (IP Address + Name), second will by secret key
	String[][] service_secretkeys;
	String mysecretkey_unhashed;
	public TGService() throws RemoteException {
//		super();
		//Obviously the '3' would be changed depending on how many fileservers there are
		//(Or if multiple directory/lock servers were going to be used
		try {
			mysecretkey_unhashed = "My super amazing secret TGS key!";
			
		} catch (Exception e) {
			e.printStackTrace();
		}
		
		service_secretkeys = new String[3][]; //Directory, Lock, FileServ
		for(int i = 0; i < service_secretkeys.length; i++){
			service_secretkeys[i] = new String[2];
		}
		//The keys have to be 16, 26, or 32 bytes
		service_secretkeys[0][0] = ""; service_secretkeys[0][1] = "My super amazing secret DIR key!";
		service_secretkeys[1][0] = ""; service_secretkeys[1][1] = "My super amazing secret LOCK key";
		service_secretkeys[2][0] = ""; service_secretkeys[2][1] = "My super amazing secret FILE key";
	}
	
	/* 
	 * Returns:
	 * [0]: USERSESSION( Client/ServiceSessionKey)
	 * [1]: USERSESSION( SERV_SECRET( ClientID ) )
	 * [2]: USERSESSION( SERV_SECRET( Client/ServiceSessionKey ) )
	 *
	 * Expect to Receive:
	 * [0]: TGSSecret( ClientID )
	 * [1]: TGSSecret( Client/TGSSessionKey )
	 * [2]: CLIENT/TGSSESSIONKEY( ServiceIDThatClientWantsAccessTo )
	 */
	public String[] getServiceSession(String[] clientmsg) throws RemoteException{
		try {
			String[] res = new String[3];
		
			byte[] mysecretkey = hashKey(mysecretkey_unhashed, 32);
			
			System.out.println("Here1: " + clientmsg[0]);
			System.out.println("Mysecretlength: " + mysecretkey.length);
			String clientID = decrypt(clientmsg[0], mysecretkey);
			
			System.out.println("Here 2");
			String sessionkey = decrypt(clientmsg[1], mysecretkey);
			String serviceID = decrypt(clientmsg[2], new BASE64Decoder().decodeBuffer(sessionkey));
			System.out.println("ClientID received: " + clientID);
			byte[] serviceSecret = findSecretKey(serviceID);
			
			String serviceSession = createSessionKey();
			
			res[0] = encrypt(serviceSession, new BASE64Decoder().decodeBuffer(sessionkey));
			//Starting service ticket:
			res[1] = encrypt( encrypt( clientID, serviceSecret ), new BASE64Decoder().decodeBuffer(sessionkey));
			res[2] = encrypt( encrypt( serviceSession, serviceSecret), new BASE64Decoder().decodeBuffer(sessionkey));
			return res;
			
		} catch (Exception e) {
			e.printStackTrace();
			return null;
		}
	}
	
	private byte[] hashKey(String s, int length){
		MessageDigest cript;
		try {
			cript = MessageDigest.getInstance("SHA-1");
			cript.reset();
			cript.update(s.getBytes("utf8"));
			//This will give a 20byte key, but we need to pad out to 24byte
			byte[] key_20byte = cript.digest();
			byte[] hashkey = new byte[length];
			int n;
			for(n = 0; n < key_20byte.length && n < length; n++){
				hashkey[n] = key_20byte[n];
			}
			for(;n < length; n++){
				hashkey[n] = 'A';
			}
			System.out.println("LEAVING LENGTH: " + hashkey.length);
			return hashkey;
		} catch (Exception e) {
			e.printStackTrace();
			return null;
		}
	
	}
	private byte[] hashKey(String s){
		return hashKey(s, 24);
	}
	
	private byte[] findSecretKey(String serviceID){
		int i;
		for(i = 0; i < service_secretkeys.length && !service_secretkeys[i][0].equals(serviceID); i++){
		}
		if(i < service_secretkeys.length)
			return service_secretkeys[i][1].getBytes();
		else
			return null;
	}
	
	private String createSessionKey(){
		Random generator = new Random();
		byte[] res = new byte[32];
		
		//Create random session key, 32 bytes long
		Integer r;
		for(int i = 0; i < res.length; i++ ){	
			r = generator.nextInt(256);
			res[i] = r.byteValue();
		}
		return new BASE64Encoder().encode(res);
	}
	
	private String encrypt(String msg, byte[] keyValue) throws Exception{
		Key key = new SecretKeySpec(keyValue, ALGORITHM);
		Cipher c = Cipher.getInstance(ALGORITHM);
		c.init(Cipher.ENCRYPT_MODE, key);
		
		String valueToEnc = msg;
		byte[] encValue = c.doFinal(new BASE64Decoder().decodeBuffer(valueToEnc));
		String eValue = new BASE64Encoder().encode(encValue);
		return eValue;
	}
	
	private String decrypt(String msg, byte[] keyValue) throws Exception{
		Key key = new SecretKeySpec(keyValue, ALGORITHM);
		Cipher c = Cipher.getInstance(ALGORITHM);
		c.init(Cipher.DECRYPT_MODE, key);
		
		byte[] decordedValue = new BASE64Decoder().decodeBuffer(msg);
		byte[] decValue = c.doFinal(decordedValue);
		String dValue = new String(decValue);
		return dValue;
	}

}